<?php
function showChk($str)
{
    $tmp = explode(' ', $str, -1);
    $tp = array();
    $num = count($tmp);

    for ($i = 0; $i < $num; $i++)
    {
        $br = '';
        if ($i % (4) == 1) //逢4输出一个br

            $br = '<br />' . $br;

        $tp[$i] = "<label>" . $tmp[$i] . "<input type=" . '"' . "checkbox" . '"' .
            "name=" . '"' . "checkbox" . '"' . "value=" . '"' . "checkbox" . '"' .
            "/></label>" . $br;
        $br = '';
    }

    return $tp;

}

function checkLoginSession()
{
    if (!isset($_SESSION['UserInfo']))
    {
        $url = U('Admin/Index');
        redirect($url);
        return;
    }
    else
    {
    setcookie('HAS_SN','' , time() + 3600 * 24 * 7, '/'); //清空历史的cookie
     $uPdo = D('user');
     $user_id = $_SESSION['UserInfo']['user_id']; 
     $mac = trim(getMac());
     $rt = $uPdo->where("`mac` = '".$mac."'" )->find();
     
     if( !($rt>0) )//user表没有mac记录
     {
     $rrt = $uPdo->execute("UPDATE `tb_user` SET `mac` = '".$mac."'  WHERE  user_id = '$user_id'" );
     setcookie('__MAC',$mac , time() + 3600 * 24 * 7, '/');
     //dump(1);
     }
     else//user表有mac记录存在
     {
     setcookie('__MAC',$mac , time() + 3600 * 24 * 7, '/');   
     setcookie('HAS_SN',$rt['HAS_SN'] , time() + 3600 * 24 * 7, '/');  
     setcookie('__SN',$rt['sn'] , time() + 3600 * 24 * 7, '/');
     }  
     
     setcookie('__NOW_APP',__SELF__ , time() + 3600 * 24, '/');         
    }  
 
}


//显示指定的表名，字段s，排序方式，搜索索引字段分页信息，需要模板配合
function ShowTable($tname, $Field, $Asc, $searchwords)
{

    if (isset($searchwords))
    {
        $sd = "1 = 1 and " . $searchwords;
    } else
    {
        $sd = "1 = 1";
    }

    $tb = D($tname);

    $list_tmp = $tb->query("SELECT count($Field) as count FROM __TABLE__ where $sd");
    $count = $list_tmp[0]["count"];

    $listRows = '10';

    $fields = '*';

    //import("ORG.Util.Page");
    import("@.ORG.Page");

    $p = new Page($count, $listRows);

    $list = $tb->where($sd)->field($fields)->order($Field.' '.$Asc)
        ->limit($p->firstRow . ',' . $p->listRows)->findall();

    $page = $p->show();

    $arrayVa['a'] = $list;
    $arrayVa['b'] = $page;
    return $arrayVa;
}

//全码查询，get方式提交，目前仅仅支持单个参数查询；支持simple_code(精确),features(部分匹配即可)
function makeSearchWord()
{
    $searchwords = ' 1 = 1';
    if (isset($_GET['simple_code']))
    {
        $searchwords = makeword('simple_code');
    }
    if (isset($_GET['features']))
    {
        $searchwords = makeLword(features);
    }

    return $searchwords;
}
function makeword($wd)
{

    $wd = $wd . " = '" . $_GET[$wd] . "'";
    return $wd;
}
function makeLword($wd)
{

    $wd = $wd . " like '%" . $_GET[$wd] . "%'";
    return $wd;

}

function operInDetlRec($str)
{ //把客户端传递来的入库详细字符串记录转化为数字key-value格式数组
    
    $tok = strtok($str, " @-");
    $i = 0;
    $j = 0;
    $datai = array();
    while ($tok !== false)
    {
        $i++;
        if (((($i - 1) % 3) == 0) and (($i - 1) > 0))
        {
            $j = $j + 1;
        }
        switch (($i % 3))
        {
            case 1:
                {$datai[$j]['simple_code'] = $tok;}                
                break;
            case 2:
                $datai[$j]['count'] = $tok;
                break;
            case 0:
                $datai[$j]['location_code'] = $tok;//库存记录的位置码为@loc-count@loc-count
                break;
            default:
                return "Error in Parseing InDepot data";
        }

        $tok = strtok("@-");
    }
    return ($datai);
}
function operOrdRec($str)
{ //下单的简码，数量字符串处理
    $tok = strtok($str, " @-");
    $i = 0;
    $j = 0;
    $datai = array();
    while ($tok !== false)
    {
        $i++;
        if (((($i - 1) % 3) == 0) and (($i - 1) > 0))
        {
            $j = $j + 1;

        }
        switch (($i % 3))
        {
            case 0:
                $datai[$j]['actual_price'] = $tok;
                break;
            case 1:
                $datai[$j]['simple_code'] = $tok;
                break;
            case 2:
                $datai[$j]['count'] = $tok;
                break;
            default:
                return "Error in Parseing InDepot data";
        }

        $tok = strtok("@-");
    }
    return ($datai);
}

function OperDpPtRec($optype, $spcode, $cnt,$loc)
{ //对depot_product操作，增加库存数量或者减少库存数量
    $dpPtPdo = D('Depot_product');
    $locPdo = D('Loc_code_count');//实时显示哪个位置存了啥，数量多少
    $userid = $_SESSION['UserInfo']['boss'];

    if ($optype == 'jia')
    {
        $rt = $dpPtPdo->where('simple_code = '."'".$spcode."'")->find();
        if($rt<1)
        {
        $rt = $dpPtPdo->execute("INSERT INTO `tb_depot_product` (`simple_code`,`real_count`,`userid`) VALUES ('$spcode','$cnt','$userid')");
        $trr =$locPdo->execute("INSERT INTO `tb_loc_code_count` (`simple_code`,`location_code`,`count`,`userid`) VALUES ('$spcode','$loc','$cnt','$userid')");
        }
        else
        {
        $rt = $dpPtPdo->execute("UPDATE `tb_depot_product` SET `real_count` = real_count + $cnt WHERE simple_code = '$spcode'");
        $trr =$locPdo->execute("UPDATE `tb_loc_code_count` SET  `count` = count + $cnt WHERE simple_code = '$spcode' and location_code = '$loc'");            
            if(!$trr)
            {
               $trr =$locPdo->execute("INSERT INTO `tb_loc_code_count` (`simple_code`,`location_code`,`count`,`userid`) VALUES ('$spcode','$loc','$cnt','$userid')"); 
            }
            ELSE
            {return "error";}
        }

    } else
    {
        if ($optype == 'jian')
        {
            $rt = $dpPtPdo->execute("UPDATE `tb_depot_product` SET `real_count` = real_count - $cnt WHERE simple_code = '$spcode'");

        }
    }

    return $rt;
}

function makeOdBaseInfo($kind, $arr)
{
    if ($kind == 'hand') //手工下单

    {
        $sn = $arr['serial_number'];
        $cust_info = $arr['cust_info'];
        $trace_note = $arr['trace_note'];
        $total_weight = $arr['total_weight'];
        $total_value = $arr['total_value'];
        $express = $arr['express'];
        $exp_number = $arr['exp_number'];
        $depot_userid = $arr['depot_userid'];
        $conductor_id = $arr['conductor_id'];
        $status = $arr['status'];
        $date = $arr['date'];
        $userid = $arr['userid'];
        $cust_note = $arr['cust_note'];

        $htmlstr = '<table><tr><td>配货单(订单)流水号：' . $sn . '</td></tr>';
        $htmlstr = $htmlstr . '<tr><td>客户信息：' . $cust_info . '</td></tr>';
        $htmlstr = $htmlstr . '<tr><td>客户备注：' . $cust_note . '</td></tr>';
        $htmlstr = $htmlstr . '<tr><td>跟踪备注：' . $trace_note . '</td></tr>';
        $htmlstr = $htmlstr . '<tr><td>总重量(克):' . $total_weight . '||总价:' . $total_value .
            '||快递:' . $express . '||快递单号:' . $exp_number . '</td></tr>';
        $htmlstr = $htmlstr . '<tr><td>销售ID:' . $conductor_id . '||商家ID:' . $userid .
            '||订单状态：' . $status . '</td></tr>';
        $htmlstr = $htmlstr . '<tr><td>下单日期：' . $date . '||配货日期：' . date('Y-m-d') .
            '</td></tr>';
        $htmlstr = $htmlstr . '</table>';

    } else
    {
        return '淘宝订单同步功能开发中';
    }

    return $htmlstr;

}

function makeLocs($dpcode, $shlfcount, $shlflayer) //把参数转换为多条数组记录
{
    $sql = "INSERT INTO __TABLE__  (`location_code`,`userid`)  VALUES ";
    $i = 1;
    $sqlstr = '';
    while ($i <= $shlfcount)
    {
        if (strlen($i) < 2)
        {
            $i = '0' . $i;
        }
        $j = 1;
        while ($j <= $shlflayer)
        {
            if (strlen($j) < 2)
            {
                $j = '0' . $j;
            }
            //$sqlstr = $sqlstr . '(' . $dpcode . $i . $j . ',' . 'cleston' . '),';
            $sqlstr = $sqlstr . '(' . "'" . $dpcode . $i . $j . "'" . ',' . "'" . $_SESSION['UserInfo']['boss'] .
                "'" . '),';
            //
            $j = $j + 1;
        }
        $i = $i + 1;
    }

    $sqlstr = substr($sqlstr, 0, strlen($sqlstr) - 1);
    return $sql . $sqlstr;

}

function exitDpcode($dpcode){//检查简码是否存在
    $ptPDO = D('Product');
    $rt = $ptPDO->where('simple_code = '."'".$dpcode."'")->find();
    if(count($rt)>0)
    return true;
    else
    return false;
}
function exitLoccode($loccode){//检查位置码是否存在
    $locPDO = D('Location');
    $userid =  $_SESSION['UserInfo']['boss'];
    $rt = $locPDO->where('location_code = '."'".$loccode."' and userid = '$userid'")->find();
    if(count($rt)>0)
    return true;
    else
    return false;  
}
function exitcount($spcode,$count){//检查位置码是否存在
      $dpPDO = D('Depot_product');
    $rt = $dpPDO->where('simple_code = '."'".$spcode."'")->find();
    if(count($rt)>0)
    return $rt[0]['real_count'];  
}

function ajaxrt($status,$msg,$data=null){//ajax 返回任何ajax请求，包括状态，消息，回传数据

if(isset($data))
$arr = array(array('status' => $status, 'data' => $data, 'msg' => $msg));
else
$arr = array(array('status' => $status, 'msg' => $msg));
$datart = json_encode($arr);
return $datart; 
    
}

function OrderLog($stapre='Pre',$stanow,$note,$orderid,$ordersn,$userid,$conduct_id){
    //涉及Order操作的主动或者自动，都要提交记录
  $logPDO = M('Order_status_log');
  $data1 = array("note"=>$note,"serial_number"=>$ordersn,"userid"=>$userid,
      "conduct_id"=>$conduct_id,"op_time"=> date('Y-m-d-G-i'),"status_pre"=>$stapre,
      "status_now"=>$stanow);  
    return $logPDO->add($data1);
}

function getLcode($simple_code,$count){//根据简码和数量获得对应位置码，可能不止一个位置码
$countx = $count;
$lcode ='';
$lccPdo = D("Loc_code_count");
$userid = $_SESSION['UserInfo']['boss'];
 $recs = $lccPdo->where("simple_code = '$simple_code'" ." and  userid = '$userid'" )->findAll();
 $reccount = count($recs);
 if($reccount>0)//有在库记录
 { $leiCount = 0;
  for ($i = 0; $i < $reccount; $i++) //逐条对比数量
  { $leiCount = $leiCount + $recs[$i]['count'];
  $lcode =  $lcode.','.$recs[$i]['location_code'].':'.$recs[$i]['count'];
    $ott = $countx - $leiCount;
    if($ott<0) return $lcode;
  } 
 }               
 else
 {
  $lcode =null;  
 }    
 return $lcode; 
}

function addinRecx($codex,$countx,$locx){//TODO把记录写入session
    
}
//获得Mac地址
function getMac(){
@exec("ipconfig /all",$array);
$Tmpa = 0;
for($Tmpa;$Tmpa<count($array);$Tmpa++)
    {
    if(eregi("Physical",$array[$Tmpa]))
    {
     $mac=explode(":",$array[$Tmpa]);
     return $mac[1];
    }
    }
}//end function

//下面是Top api的辅助函数
//签名函数 
function createSign ($paramArr) { 
    global $appSecret; 
    $sign = $appSecret; 
    ksort($paramArr); 
    foreach ($paramArr as $key => $val) { 
       if ($key !='' && $val !='') { 
           $sign .= $key.$val; 
       } 
    } 
    $sign = strtoupper(md5($sign));  //Hmac方式
//    $sign = strtoupper(md5($sign.$appSecret)); //Md5方式	
    return $sign; 
}

//组参函数 
function createStrParam ($paramArr) { 
    $strParam = ''; 
    foreach ($paramArr as $key => $val) { 
       if ($key != '' && $val !='') { 
           $strParam .= $key.'='.urlencode($val).'&'; 
       } 
    } 
    return $strParam; 
} 

//解析xml函数
function getXmlData ($strXml) {
	$pos = strpos($strXml, 'xml');
	if ($pos) {
		$xmlCode=simplexml_load_string($strXml,'SimpleXMLElement', LIBXML_NOCDATA);
		$arrayCode=get_object_vars_final($xmlCode);
		return $arrayCode ;
	} else {
		return '';
	}
}
	
function get_object_vars_final($obj){
	if(is_object($obj)){
		$obj=get_object_vars($obj);
	}
	if(is_array($obj)){
		foreach ($obj as $key=>$value){
			$obj[$key]=get_object_vars_final($value);
		}
	}
	return $obj;
}

//验证签名
function validateSign($sign,$parameter){
    $rt =null;
 if(($sign!=null) and ($parameter!=null))
 {
    $rt=createSign($parameter)==$sign?true:false;
 }  
 return $rt; 
}

function addToLocalOrd($arr){
$reccnt = $arr['trades_sold_increment_get_response']['total_results'];
//echo($reccnt);
$trade = $arr['trades_sold_increment_get_response']['trades']['trade'];
//dump($trade);
$ordPdo = D('Order');
$orddtlPdo = D('Order_detail');
while($reccnt>0)
{
    $tid=$trade[$reccnt-1]['tid'];
    $ordcnt = count($trade[$reccnt-1]['orders']['order']);//订单的详单个数
    $seller_memo = $trade[$reccnt-1]['seller_memo'];
    $tvl = $trade[$reccnt-1]['total_fee'];
    //dump($trade[$reccnt-1]['orders']['order']);
    //echo($ordcnt);
    $rtttt = $ordPdo->where("tid = '$tid'")->find();
    if($rtttt)
    {
        //update 订单信息的状态和客户备注和客服备注，订单总价格
        $idd = $rtttt['id_tb_order'];
        $tvl = $trade[$reccnt-1]['total_fee'];
        $status = $trade[$reccnt-1]['status'];
        $sqlup = "UPDATE `tb_order` SET `total_value` = $tvl , `status`='$status',`trace_note` = '$seller_memo'   WHERE  id_tb_order = $idd";
        $rr3t = $ordPdo->execute($sqlup);        
    }
    else
    {    //insert 订单信息   
        $status = $trade[$reccnt-1]['status']; 
        $custname = $trade[$reccnt-1]['receiver_name']; //收货人姓名，不一定是买家真实姓名   
        $custid=$trade[$reccnt-1]['buyer_nick'];
        $addr = $trade[$reccnt-1]['receiver_address'];
        $mobile =  $trade[$reccnt-1]['receiver_mobile'];
        $phone =  isset($trade[$reccnt-1]['receiver_phone'])?$trade[$reccnt-1]['receiver_phone']:NULL;
        $bossid = $_SESSION['UserInfo']['boss'];;
        $conductid= $_SESSION['UserInfo']['user_id'];
        $alipay_no = $trade[$reccnt-1]['alipay_no'];
        $email = $trade[$reccnt-1]['buyer_email'];
        $buyer_message = isset($trade[$reccnt-1]['buyer_message'])?$trade[$reccnt-1]['buyer_message']:NULL;        
        $datex = date('Y-m-d');        
        $sn = str_ireplace('-','',$trade[$reccnt-1]['created']);
        $sn = str_ireplace(' ','',$sn);
        $sn = str_ireplace(':','',$sn);
        $dataord = array("serial_number" => $sn,'custmer_id'=>$custid,"conductor_id" => $conductid, "date" => date('Y-m-d'),
                    "cust_note" =>$buyer_message,"status"=>$status,'total_value'=>$tvl,"userid" => $bossid,'customer_phone'=>$phone,
                    'custmer_name'=>$custname,'address'=>$addr,'trace_note'=>$seller_memo,'status'=>$status,
                    'customer_email'=>$email,'tid'=>$tid,'customer_mobile'=>$mobile,'alipay_no'=>$alipay_no);
        //$sqlist = "INSERT INTO `tb_order` VALUES (NULL, '$sn', '$custid', '$custname', '$addr', NULL, NULL,NULL, '$buyer_message', 
        //'$seller_memo', '$status', $tvl, '$conductid', '$bossid', '$phone', '$email','$datex', NULL, NULL, 'sale', 'taobao',NULL,'$tid',
        //'$mobile','$alipay_no');";
        //$rr8t = $ordPdo->execute($sqlist);
        $rr8t =  $ordPdo->add($dataord);     
        if($rr8t)
        {
            while($ordcnt>0)
            {            
                $oid = $trade[$reccnt-1]['orders']['order'][$ordcnt-1]['oid'];
                $outer_iid = $trade[$reccnt-1]['orders']['order'][$ordcnt-1]['outer_iid'];
                $num = $trade[$reccnt-1]['orders']['order'][$ordcnt-1]['num'];
                $tprice = $num * $trade[$reccnt-1]['orders']['order'][$ordcnt-1]['price'];
                $sqlorddist = "INSERT INTO `tb_order_detail` VALUES (NULL,'$rr8t','$outer_iid',$num,$tprice,NULL,'$sn',NULL,NULL,'$oid');";
                //dump($sqlorddist);
                $tt99 = $orddtlPdo->execute($sqlorddist);
                $ordcnt = $ordcnt-1;//把每个详单insert进去
            }
        }
    }
    
    $reccnt =$reccnt-1;
}

    
    
    return true; 
}

?>